package com.liukai.todo_android.ui.dialog;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatSpinner;

import com.liukai.todo_android.R;
import com.liukai.todo_android.call_back.IAddScheduleCallBack;
import com.liukai.todo_android.call_back.IUpdateScheduleCallBack;
import com.liukai.todo_android.common.utils.Constants;
import com.liukai.todo_android.common.utils.LogUtils;
import com.liukai.todo_android.entity.ItemVo;
import com.liukai.todo_android.entity.Resp;
import com.liukai.todo_android.entity.vo.InsertItemVo;
import com.liukai.todo_android.entity.vo.UpdateItemVo;
import com.liukai.todo_android.presenter.AddSchedulePresenter;
import com.liukai.todo_android.presenter.UpdateSchedulePresenter;

/**
 * @author ：liukai
 * @date ：Created in 2021/8/13 5:36 下午
 * @description：新增待办的对话框
 * @modified By：
 * @version: $
 */
public class AddOrUpdateScheduleDialog implements IAddScheduleCallBack, IUpdateScheduleCallBack {

    private Context context;
    private int layoutId = R.layout.dialog_add_schedule;
    private View view;
    private AlertDialog dialog;
    private AppCompatSpinner timingTypeSpinner;
    private AppCompatSpinner scheduleTypeSpinner;
    private AppCompatButton btnSubmitAttach;
    private TextView btnSave;
    private TextView btnCancel;
    private EditText etScheduleTitle;
    private EditText etScheduleDesc;
    private Integer timingType;
    private EditText etPlanTime;

    private ItemVo itemVo;

    public static final int MODEL_ADD = 0;
    public static final int MODEL_UPDATE = 1;
    public static final int MODEL_HISTORY_UPDATE = 2;
    public static final String ADD_NAME = "新增";
    public static final String UPDATE_NAME = "编辑";

    private int dialogModel = MODEL_ADD;
    private TextView dialogTitle;

    public AddOrUpdateScheduleDialog(Context context, int model) {
        this.context = context;
        this.dialogModel = model;
        createDialog();
        initView();
        initListener();
    }

    public AddOrUpdateScheduleDialog(Context context, int model, ItemVo itemVo) {
        this.context = context;
        this.dialogModel = model;
        this.itemVo = itemVo;
        createDialog();
        initView();
        initDate();
        initListener();
    }

    private void initView() {

        ArrayAdapter<String> timingTypeAdapter = new ArrayAdapter<>(context,
                R.layout.support_simple_spinner_dropdown_item);
        timingTypeSpinner = view.findViewById(R.id.timing_type);
        scheduleTypeSpinner = view.findViewById(R.id.schedule_type);
        btnSubmitAttach = view.findViewById(R.id.submit_attach);
        btnSave = view.findViewById(R.id.btn_save);
        btnCancel = view.findViewById(R.id.btn_cancel);
        etScheduleTitle = view.findViewById(R.id.schedule_title);
        etScheduleDesc = view.findViewById(R.id.schedule_desc);
        etPlanTime = view.findViewById(R.id.planTime);
        dialogTitle = view.findViewById(R.id.dialog_title);

        if (dialogModel == MODEL_ADD) {
            dialogTitle.setText(ADD_NAME);
            return;
        }
        if (dialogModel == MODEL_UPDATE) {
            dialogTitle.setText(UPDATE_NAME);
            return;
        }
        if (dialogModel == MODEL_HISTORY_UPDATE) {
            dialogTitle.setText(UPDATE_NAME);
            timingTypeSpinner.setEnabled(false);
            scheduleTypeSpinner.setEnabled(false);
            btnSubmitAttach.setEnabled(false);
        }

    }

    private void initDate() {
        scheduleTypeSpinner.setSelection(2, true);
        etScheduleTitle.setText(itemVo.getTitle());
        etScheduleDesc.setText(itemVo.getDescription());
    }

    private void initListener() {

        initTimingTypeListener();
        initCancelListener();
        initSaveListener();

    }

    /**
     * 取消
     */
    private void initCancelListener() {
        btnCancel.setOnClickListener(v -> {
            this.dismiss();
        });
    }

    /**
     * 保存
     */
    private void initSaveListener() {
        btnSave.setOnClickListener(v -> {
            if (dialogModel == MODEL_ADD) {
                saveClick(v);
                return;
            }
            if (dialogModel == MODEL_UPDATE || dialogModel == MODEL_HISTORY_UPDATE) {
                updateClick(v);
                return;
            }
        });
    }

    /**
     * 新增保存
     *
     * @param v
     */
    private void saveClick(View v) {
        InsertItemVo insertItemVo = createInsertItemVO();
        AddSchedulePresenter addSchedulePresenter = new AddSchedulePresenter();
        addSchedulePresenter.registerCallback(this);
        addSchedulePresenter.addSchedule(insertItemVo, context);
        this.dismiss();
    }

    /**
     * 修改保存
     *
     * @param v
     */
    private void updateClick(View v) {
        UpdateItemVo updateItemVo = createUpdateItemVO();
        UpdateSchedulePresenter updateSchedulePresenter = new UpdateSchedulePresenter();
        updateSchedulePresenter.registerCallback(this);
        updateSchedulePresenter.update(updateItemVo);
        this.dismiss();
    }

    /**
     * 创建一个UpdateScheduleVo对象
     */
    private UpdateItemVo createUpdateItemVO() {
        String scheduleTitle = etScheduleTitle.getText().toString();
        String scheduleDesc = etScheduleDesc.getText().toString();
        itemVo.setTitle(scheduleTitle);
        itemVo.setDescription(scheduleDesc);
        UpdateItemVo updateItemVo = UpdateItemVo.build(itemVo);
        // 只有倒计时才会有计划时间
        if (etPlanTime.getVisibility() == View.VISIBLE) {
            Integer planTime = Integer.valueOf(etPlanTime.getText().toString());
            updateItemVo.setConsumePlanning(planTime * 60);
        }
        return updateItemVo;
    }

    /**
     * 创建一个InsertScheduleVo对象
     */
    private InsertItemVo createInsertItemVO() {
        String scheduleTitle = etScheduleTitle.getText().toString();
        String scheduleDesc = etScheduleDesc.getText().toString();
        Long userId = Constants.getUserId(context);
        InsertItemVo insertItemVo = new InsertItemVo();
        insertItemVo.setUserId(userId)
                .setTitle(scheduleTitle)
                .setDescription(scheduleDesc)
                .setTimingType(Byte.valueOf(timingType + ""));
        // 只有倒计时才会有计划时间
        if (etPlanTime.getVisibility() == View.VISIBLE) {
            Integer planTime = Integer.valueOf(etPlanTime.getText().toString());
            insertItemVo.setConsumePlanning(planTime * 60);
        }
        return insertItemVo;
    }

    /**
     * 选择计时类型
     */
    private void initTimingTypeListener() {
        timingTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String result = parent.getItemAtPosition(position).toString();
                Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
                if (position == Constants.TIMING_TYPE_DOWN) {
                    etPlanTime.setVisibility(View.VISIBLE);
                    if (dialogModel == MODEL_UPDATE && itemVo.getTimingType() == Constants.TIMING_TYPE_DOWN) {
                        etPlanTime.setText(itemVo.getConsumePlanning() + "");
                    }
                } else {
                    etPlanTime.setVisibility(View.GONE);
                }
                timingType = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 创建新增对话框
     */
    private void createDialog() {
        view = View.inflate(context, layoutId, null);
        dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        // 设置点击可取消
        dialog.setCancelable(true);
        // 获取Window对象
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        // 设置显示视图内容
        window.setContentView(view);
    }

    public void dismiss() {
        dialog.dismiss();
    }

    @Override
    public void addError(Resp resp) {
        LogUtils.e(getClass(), resp.toString());
    }

    @Override
    public void addSuccess(Resp resp) {
        LogUtils.e(getClass(), resp.toString());
        onAddSuccessListener.addSuccess();
    }

    @Override
    public void updateScheduleSuccess(Resp resp) {
        LogUtils.e(getClass(), resp.toString());
        onUpdateSuccessListener.updateSuccess();
    }

    @Override
    public void updateScheduleError(Resp resp) {

    }

    public interface OnAddSuccessListener {
        void addSuccess();
    }

    private OnAddSuccessListener onAddSuccessListener;

    public void setOnSuccessListener(OnAddSuccessListener onAddSuccessListener) {
        this.onAddSuccessListener = onAddSuccessListener;
    }

    public interface OnUpdateSuccessListener {
        void updateSuccess();
    }

    private OnUpdateSuccessListener onUpdateSuccessListener;

    public void setOnUpdateSuccessListener(OnUpdateSuccessListener onUpdateSuccessListener) {
        this.onUpdateSuccessListener = onUpdateSuccessListener;
    }
}
